TAB_SPACE = '   '


class ScriptTemplate:
    prefix_tab: str = ''

    def reset(self) -> str: ...

    def click(self, resource_id: str) -> str: ...

    def swipe(self, x: int, y: int, to_x: int, to_y: int, duration: float) -> str: ...

    def sleep(self, second: int) -> str: ...

    def allure_feature_story(self, feature_name: str = '', story_name: str = '') -> str:
        feature_code = ''
        if len(feature_name) > 0:
            feature_code = f"{self.prefix_tab}@allure.feature('{feature_name}')\n"
        result = ("\n\n\n"
                  + feature_code
                  + f"{self.prefix_tab}@allure.story('{story_name}')\n"
                  + f"{self.prefix_tab}def test_{story_name}():\n")
        self.tab()
        return result

    def allure_step(self, step_name: str = '') -> str:
        result = f"\n{self.prefix_tab}with allure.step('{step_name}'):"
        self.tab()
        return result

    def tab(self):
        self.prefix_tab = self.prefix_tab + TAB_SPACE

    def tab_restore(self):
        self.prefix_tab = self.prefix_tab[:-len(TAB_SPACE)]

    def stop(self):
        self.prefix_tab = ''


class U2ScriptTemplate(ScriptTemplate):
    def reset(self) -> str:
        self.prefix_tab = ''
        return ("#coding: utf-8\n"
                "import uiautomator2 as u2\n"
                "import allure\n"
                "import pytest\n"
                "import time\n\n"
                "print('code style by QsciScintilla')\n"
                "d = u2.connect()\n"
                "print(d.device_info)\n")

    def click(self, resource_id: str) -> str:
        return f"\n{self.prefix_tab}d(resourceId='{resource_id}').click()"

    def swipe(self, x: int, y: int, to_x: int, to_y: int, duration: float = 0.1) -> str:
        x = round(x, 2)
        y = round(y, 2)
        to_x = round(to_x, 2)
        to_y = round(to_y, 2)
        duration = round(duration, 1)
        return f"\n{self.prefix_tab}d.swipe({x}, {y}, {to_x}, {to_y}, {duration})"

    def sleep(self, second: int) -> str:
        return f"\n{self.prefix_tab}time.sleep({second})"


coder = U2ScriptTemplate()
